import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 设置英文和数字的字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
# 加载数据
data = pd.read_excel('sum_time_07.xlsx')
# 筛选只包含 "crown" 的列
crown_columns = [col for col in data.columns if 'crown' in col]
crown_columns.insert(0, 'clade')  # 将 'clade' 列包含在内
data_crown = data[crown_columns]
# 清理 clade 列中的非 ASCII 字符和括号
data_crown = data_crown.copy()  # 确保data_crown是独立的DataFrame
data_crown.loc[:, 'clade'] = data_crown['clade'].apply(lambda x: ''.join([i for i in str(x) if ord(i) < 128 and i not in ['(', ')', '[', ']', '{', '}', '<', '>']]))
# 将区间字符串转换为数值并提取每个区间的下限和上限，计算中点
for col in data_crown.columns[1:]:
    data_crown.loc[:, col] = data_crown[col].apply(lambda x: (float(x.split('-')[0]) + float(x.split('-')[1])) / 2 if isinstance(x, str) else x)
# 将数据转换为长格式，以便于绘图
data_long = pd.melt(data_crown, id_vars=['clade'], var_name='time_type', value_name='time_interval')
plt.figure(figsize=(16, 12))
sns.barplot(x='clade', y='time_interval', hue='time_type', data=data_long, palette='viridis')
# 添加标题和标签
plt.title('Time of differentiation of species crown groups')
plt.xlabel('Species')
plt.ylabel('Differentiation time (billions of years)')
# 调整x轴标签的旋转角度和字体大小
plt.xticks(rotation=90, fontsize=15)
# 获取 y 轴的最小值和最大值
y_min = data_long['time_interval'].min()
y_max = data_long['time_interval'].max()
# 设置y轴的刻度间隔
plt.yticks(range(int(y_min), int(y_max) + 1))
# 调整图例位置
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)
# 显示图表
plt.tight_layout()
plt.show()